import { ref, createVNode, render } from 'vue';
import Loading from '../components/commont/Loader.vue';  // 引入 Loading 组件

// 类型导入 VNode
import type { VNode } from 'vue';

// 定义一个接口来描述传入的 options 参数
interface LoadingOptions {
  text?: string;
  backgroundColor?: string;
}

export const useLoading = () => {
  const loadingInstance = ref<HTMLDivElement | null>(null);  // 存储加载器实例

  // 显示加载器
  const showLoading = (options: LoadingOptions = {}): void => {
    const { text = 'Loading...', backgroundColor = 'rgba(0, 0, 0, 0.7)' } = options;

    // 创建一个虚拟的 DOM 节点并挂载
    const vnode: VNode = createVNode(Loading, {
      text,
      backgroundColor,
      visible: true,
    });

    const div = document.createElement('div');
    render(vnode, div);
    document.body.appendChild(div);

    loadingInstance.value = div;  // 保存加载器实例
  };

  // 关闭加载器
  const closeLoading = (): void => {
    if (loadingInstance.value) {
      render(null, loadingInstance.value);  // 移除虚拟 DOM 节点
      document.body.removeChild(loadingInstance.value);  // 从 DOM 中移除
      loadingInstance.value = null;
    }
  };




  const handleLoading = (isLoading: boolean, message: string = '', backgroundColor: string = 'rgba(35, 33, 33, 0.5)') => {
    if (isLoading) {
      showLoading({
        text: message,
        backgroundColor: backgroundColor,
      });
    } else {
      closeLoading();
    }
  };



  return {
    handleLoading
  };
};
